﻿using System;
using K9Nano.Dependency;
using K9Nano.Domain;
using K9Nano.EFCore;
using Microsoft.EntityFrameworkCore;

namespace Microsoft.Extensions.DependencyInjection
{
    public static class EfCoreStartupExtensions
    {
        public static IK9NanoAppBuilder AddEfCore<TDbContext>(this IK9NanoAppBuilder builder,
            Action<DbContextOptionsBuilder> dbSetupAction)
            where TDbContext : DbContext
        {
            // Can not use Pool as Filters access some scoped values，e.g. TenantId
            builder.Services.AddDbContext<TDbContext>(dbSetupAction);

            var uowImplType = typeof(EfCoreUnitOfWork<>).MakeGenericType(typeof(TDbContext));
            builder.Services.AddScoped(typeof(IUnitOfWork), uowImplType);

            builder.Services.RegisterConventionalAssembly(typeof(EfCoreStartupExtensions).Assembly);

            return builder;
        }
    }
}
